﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace RegisterationCommon.Common
{
    /// <summary>
    /// 操作cookie
    /// </summary>
    public static class Cookies
    {
        private static string CookiesGroupName = "RoboRegisteration";
        /// <summary>
        /// 设置cookies
        /// </summary>
        /// <param name="mainName">主键</param>
        /// <param name="mainValue">值</param>
        /// <param name="days">天数</param>
        /// <returns></returns>
        public static bool Set(string key, string val)
        {
            HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies[CookiesGroupName];
            if (cookie == null)
            {
                cookie = new HttpCookie(CookiesGroupName);
            }

            cookie.Values.Set(key, HttpUtility.UrlDecode(val));
            //cookie.Expires = DateTime.Now.AddDays(3);  //设定Cookies十四后过期
            System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
            return true;
        }

        /// <summary>
        /// 根据键名获取cookies
        /// </summary>
        /// <param name="key">主键</param>
        /// <returns></returns>
        public static string Get(string key)
        {
            HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies[CookiesGroupName];
            if (cookie != null)
            {
                try
                {
                    return cookie.Values[key].ToString();
                }
                catch (Exception)
                {

                    return null;
                }

            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 判断Cookies是否存在
        /// </summary>
        /// <returns></returns>
        public static bool Exists()
        {
            return System.Web.HttpContext.Current.Request.Cookies[CookiesGroupName] == null ? false : true;
        }

        /// <summary>
        /// 注销Cookies
        /// </summary>
        public static void Clear()
        {
            if (Exists())
            {
                HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies[CookiesGroupName];
                cookie.Expires = DateTime.Now.AddDays(-1);
                System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
            }
        }
    }
}
